<template>
  <div class="work-order-inspection-page">
    <el-card class="card-block breadcrumb-card">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>质量管理</el-breadcrumb-item>
        <el-breadcrumb-item>工单检验</el-breadcrumb-item>
        <el-breadcrumb-item>新增工单检验</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>

    <el-card class="card-block form-card">
      <div class="page-header">
        <div>
          <h2>新增工单检验</h2>
          <p class="page-desc">录入工单检验信息、检验项目及结果并同步检测方案</p>
        </div>
        <div class="header-actions">
          <el-button @click="handleBack">返回</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">保存并提交</el-button>
        </div>
      </div>

      <el-form ref="formRef" :model="formModel" :rules="rules" label-width="120px" class="inspection-form">
        <el-divider content-position="left">检验单信息</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="检验单编号" prop="inspectionCode">
              <el-input v-model="formModel.inspectionCode" :disabled="formModel.useSystemCode" placeholder="请输入检验单编号">
                <template #suffix>
                  <span class="system-flag">
                    <span>系统编号</span>
                    <el-switch
                      v-model="formModel.useSystemCode"
                      size="small"
                      inline-prompt
                      active-text="是"
                      inactive-text="否"
                      @change="handleCodeModeChange"
                    />
                  </span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验单名称">
              <el-input v-model="formModel.inspectionName" placeholder="请输入检验单名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="检验日期" prop="inspectionDate">
              <el-date-picker
                v-model="formModel.inspectionDate"
                type="date"
                placeholder="请选择检验日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验部门" prop="departmentPath">
              <div class="department-selector">
                <el-input v-model="formModel.departmentBreadcrumb" placeholder="请选择检验部门" readonly />
                <el-button type="primary" @click="openDepartmentDialog">选择</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="检验人" prop="inspectors">
              <div class="inspectors-input">
                <el-tag
                  v-for="item in formModel.inspectors"
                  :key="item.userId"
                  type="info"
                  closable
                  @close="removeInspector(item.userId)"
                >
                  {{ item.userName }}
                </el-tag>
                <el-button size="small" @click="openInspectorDialog">选择</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="formModel.remark" placeholder="请输入备注信息" clearable />
        </el-form-item>

        <el-divider content-position="left">生产计划信息</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="formModel.planName" placeholder="请选择生产计划" readonly>
                <template #append>
                  <el-button @click="openPlanDialog">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划编号">
              <el-input v-model="formModel.planCode" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="工单名称">
              <el-input v-model="formModel.workOrderName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单编号">
              <el-input v-model="formModel.workOrderCode" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="产品名称">
              <el-input v-model="formModel.productName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品编号">
              <el-input v-model="formModel.productCode" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="规格型号">
              <el-input v-model="formModel.specification" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位">
              <el-input v-model="formModel.unit" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="批次号">
              <el-input v-model="formModel.batchNo" placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测方案">
              <el-input :model-value="planInfo?.planname || ''" readonly placeholder="请选择工单后自动关联" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">检验项目</el-divider>
        <el-alert
          v-if="!planInfo"
          title="请选择已配置检测方案的工单，系统会自动加载检测项目与缺陷要求"
          type="warning"
          show-icon
          class="mb-12"
        />
        <el-table
          :data="planItems"
          border
          stripe
          style="width: 100%"
          v-loading="planLoading"
          empty-text="请选择工单后自动加载检测项目"
        >
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="testitemname" label="检测项目名称" min-width="150" />
          <el-table-column prop="testitemcard" label="检测项目编号" min-width="140" />
          <el-table-column prop="detectiontypename" label="检测类型" min-width="120" />
          <el-table-column prop="detectiontoolname" label="检测工具" min-width="140" />
          <el-table-column prop="detectionrequirement" label="检测要求" min-width="180" />
          <el-table-column prop="standardvalue" label="标准值" min-width="120" />
          <el-table-column prop="unit" label="单位" width="90" />
          <el-table-column prop="toleranceupper" label="误差上限" width="120" />
          <el-table-column prop="tolerancelower" label="误差下限" width="120" />
          <el-table-column label="检测值" min-width="140">
            <template #default="scope">
              <el-input v-model="scope.row.measuredvalue" placeholder="请输入检测值" />
            </template>
          </el-table-column>
          <el-table-column label="判定结果" width="130">
            <template #default="scope">
              <el-select v-model="scope.row.result" placeholder="请选择">
                <el-option label="合格" value="合格" />
                <el-option label="不合格" value="不合格" />
              </el-select>
            </template>
          </el-table-column>
        </el-table>

        <el-divider content-position="left">缺陷判定</el-divider>
        <template v-if="planInfo">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="最大不合格数">
              <span v-if="planInfo.enablemaxunqualified">{{ planInfo.maxunqualifiedcount ?? "-" }}</span>
              <span v-else>未启用</span>
            </el-descriptions-item>
            <el-descriptions-item label="致命缺陷率(%)">
              <span v-if="planInfo.enablecriticaldefectrate">{{ planInfo.criticaldefectrate ?? "-" }}</span>
              <span v-else>未启用</span>
            </el-descriptions-item>
            <el-descriptions-item label="严重缺陷率(%)">
              <span v-if="planInfo.enablemajordefectrate">{{ planInfo.majordefectrate ?? "-" }}</span>
              <span v-else>未启用</span>
            </el-descriptions-item>
            <el-descriptions-item label="轻微缺陷率(%)">
              <span v-if="planInfo.enableminordefectrate">{{ planInfo.minordefectrate ?? "-" }}</span>
              <span v-else>未启用</span>
            </el-descriptions-item>
            <el-descriptions-item label="检测分类">{{ planInfo.detectioncategory }}</el-descriptions-item>
            <el-descriptions-item label="检测种类">{{ planInfo.inspectiontype }}</el-descriptions-item>
          </el-descriptions>
        </template>
        <el-empty v-else description="暂无检测方案信息" />

        <el-divider content-position="left">检验结果</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="检测数量" prop="inspectionQty">
              <el-input-number v-model="formModel.inspectionQty" :min="0" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合格数量" prop="qualifiedQty">
              <el-input-number v-model="formModel.qualifiedQty" :min="0" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="不合格数量" prop="unqualifiedQty">
              <el-input-number v-model="formModel.unqualifiedQty" :min="0" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="致命缺陷数">
              <el-input-number v-model="formModel.criticalDefectQty" :min="0" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="严重缺陷数">
              <el-input-number v-model="formModel.majorDefectQty" :min="0" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="轻微缺陷数">
              <el-input-number v-model="formModel.minorDefectQty" :min="0" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="检验结果">
              <el-tag :type="formModel.resultStatus === '合格' ? 'success' : 'danger'" effect="dark">
                {{ formModel.resultStatus }}
              </el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结果备注">
              <el-input v-model="formModel.resultRemark" placeholder="请输入结果备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 检验人对话框 -->
    <el-dialog v-model="inspectorDialogVisible" title="选择检验人员" width="720px">
      <div class="inspector-dialog">
        <div class="inspector-left">
          <el-empty v-if="!formModel.departmentPath.length" description="请选择检验部门后再选择人员" />
          <template v-else>
            <div class="inspector-search">
              <el-input
                v-model="inspectorKeyword"
                placeholder="输入姓名搜索"
                clearable
                @clear="handleInspectorSearch"
                @input="handleInspectorSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            <el-table
              :data="filteredInspectorList"
              height="360px"
              border
              @selection-change="handleInspectorSelection"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="userName" label="姓名" />
            </el-table>
          </template>
        </div>
        <div class="inspector-right">
          <div class="inspector-right-header">
            <span>已选 {{ inspectorSelection.length }} 人</span>
            <el-button text type="danger" size="small" @click="clearInspectorSelection">清空</el-button>
          </div>
          <div class="inspector-tag-list">
            <el-empty v-if="!inspectorSelection.length" description="暂未选择人员" />
            <el-tag
              v-for="item in inspectorSelection"
              :key="item.userId"
              type="info"
              closable
              @close="removeDialogInspector(item.userId)"
            >
              {{ item.userName }}
            </el-tag>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="inspectorDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmInspectors">确定</el-button>
      </template>
    </el-dialog>

    <!-- 检验部门选择 -->
    <el-dialog v-model="departmentDialogVisible" title="选择检验部门" width="480px">
      <el-tree
        :data="departmentOptions"
        node-key="value"
        :props="departmentProps"
        highlight-current
        @node-click="handleDepartmentNodeClick"
        style="max-height: 420px; overflow: auto"
      />
      <template #footer>
        <el-button @click="cancelDepartmentSelection">取消</el-button>
        <el-button type="primary" @click="confirmDepartmentSelection">确定</el-button>
      </template>
    </el-dialog>

    <!-- 生产计划选择 -->
    <el-dialog v-model="planDialogVisible" title="选择生产计划" width="900px" @open="fetchPlanList">
      <el-form :inline="true" :model="planQueryForm" label-width="auto" class="dialog-filter">
        <el-form-item label="计划编号/名称">
          <el-input v-model="planQueryForm.keyword" placeholder="请输入计划编号或名称" clearable />
        </el-form-item>
        <el-form-item label="产品名称">
          <el-input v-model="planQueryForm.productName" placeholder="请输入产品名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlePlanQuery">查询</el-button>
          <el-button @click="resetPlanQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="planTableData"
        border
        stripe
        height="420px"
        v-loading="planTableLoading"
        @current-change="handlePlanRowChange"
        highlight-current-row
      >
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column prop="planCode" label="计划编号" min-width="140" />
        <el-table-column prop="planName" label="计划名称" min-width="140" />
        <el-table-column prop="productName" label="产品名称" min-width="140" />
        <el-table-column prop="productId" label="产品编号" min-width="140" />
        <el-table-column prop="productmodelsame" label="规格型号" min-width="140" />
        <el-table-column prop="productunit" label="单位" width="80" />
        <el-table-column prop="planCount" label="计划数量" width="100" />
        <el-table-column prop="workOrderCount" label="工单数量" width="100" />
      </el-table>
      <el-pagination
        v-model:current-page="planPagination.pageIndex"
        v-model:page-size="planPagination.pageSize"
        background
        layout="total, sizes, prev, pager, next"
        :total="planPagination.totalCount"
        :page-sizes="[10, 20, 30, 50]"
        @size-change="handlePlanSizeChange"
        @current-change="handlePlanPageChange"
        style="margin-top: 12px"
      />
      <template #footer>
        <el-button @click="planDialogVisible = false">取消</el-button>
        <el-button type="primary" :disabled="!currentPlan" @click="handlePlanConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ArrowRight, Search } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import https from '@/Http/http'

interface ApiResultResponse<T> {
  code: number
  msg: string
  data: T
}

interface ApiPageResponse<T> {
  code: number
  msg: string
  data: T[]
  totalCount: number
}

interface DepartmentNode {
  value: number
  label: string
  children?: DepartmentNode[]
}

interface InspectorUser {
  userId: number
  userName: string
}

interface WorkOrderInspectionPlan {
  planid: number
  plancode: string
  planname: string
  detectioncategory: string
  inspectiontype: string
  enabledefectsetting: boolean
  enablemaxunqualified: boolean
  maxunqualifiedcount?: number
  enablecriticaldefectrate: boolean
  criticaldefectrate?: number
  enablemajordefectrate: boolean
  majordefectrate?: number
  enableminordefectrate: boolean
  minordefectrate?: number
  product?: {
    productid: number
    productcode: string
    productname: string
    specification?: string
    unit?: string
  }
  items: WorkOrderInspectionPlanItem[]
}

interface WorkOrderInspectionPlanItem {
  id: number
  planid: number
  testitemid?: number
  testitemcard?: string
  testitemname?: string
  detectiontypename?: string
  detectiontoolname?: string
  detectionrequirement?: string
  standardvalue?: string
  unit?: string
  toleranceupper?: number
  tolerancelower?: number
  sortorder?: number
}

interface PlanItemRow extends WorkOrderInspectionPlanItem {
  measuredvalue?: string
  result?: string
}


const router = useRouter()
const route = useRoute()
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

const formModel = reactive({
  inspectionCode: '',
  inspectionName: '',
  useSystemCode: true,
  inspectionDate: '',
  departmentPath: [] as (string | number)[],
  departmentBreadcrumb: '',
  inspectors: [] as InspectorUser[],
  remark: '',
  planId: undefined as number | undefined,
  planCode: '',
  planName: '',
  workOrderId: undefined as number | undefined,
  workOrderCode: '',
  workOrderName: '',
  productId: undefined as number | undefined,
  productCode: '',
  productName: '',
  specification: '',
  unit: '',
  batchNo: '',
  inspectionQty: null as number | null,
  qualifiedQty: null as number | null,
  unqualifiedQty: null as number | null,
  criticalDefectQty: null as number | null,
  majorDefectQty: null as number | null,
  minorDefectQty: null as number | null,
  resultStatus: '合格',
  resultRemark: ''
})

const rules = reactive<FormRules>({
  inspectionCode: [{ required: true, message: '请输入检验单编号', trigger: 'blur' }],
  inspectionDate: [{ required: true, message: '请选择检验日期', trigger: 'change' }],
  departmentPath: [{ required: true, message: '请选择检验部门', trigger: 'change' }],
  inspectors: [
    {
      validator: (_rule, value, callback) => {
        if (!value || !value.length) {
          callback(new Error('请选择检验人员'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  planName: [{ required: true, message: '请选择生产计划', trigger: 'change' }],
  inspectionQty: [{ required: true, message: '请输入检测数量', trigger: 'blur' }],
  unqualifiedQty: [{ required: true, message: '请输入不合格数量', trigger: 'blur' }],
  qualifiedQty: [{ required: true, message: '请输入合格数量', trigger: 'blur' }]
})

const departmentOptions = ref<DepartmentNode[]>([])
const departmentProps = {
  children: 'children',
  label: 'label'
}

const planInfo = ref<WorkOrderInspectionPlan | null>(null)
const planItems = ref<PlanItemRow[]>([])
const planLoading = ref(false)

// 生产计划相关
const planDialogVisible = ref(false)
const planTableLoading = ref(false)
const planQueryForm = reactive({
  keyword: '',
  productName: ''
})
const planTableData = ref<any[]>([])
const planPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0
})
const currentPlan = ref<any | null>(null)

const inspectorDialogVisible = ref(false)
const inspectorList = ref<InspectorUser[]>([])
const inspectorSelection = ref<InspectorUser[]>([])
const inspectorKeyword = ref('')

const filteredInspectorList = computed(() => {
  if (!inspectorKeyword.value) {
    return inspectorList.value
  }
  return inspectorList.value.filter((item) =>
    item.userName.toLowerCase().includes(inspectorKeyword.value.toLowerCase())
  )
})


const handleCodeModeChange = () => {
  if (formModel.useSystemCode) {
    formModel.inspectionCode = generateCode()
  } else {
    formModel.inspectionCode = ''
  }
}

const generateCode = () => {
  const now = new Date()
  return `GDJY${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now
    .getDate()
    .toString()
    .padStart(2, '0')}${now.getHours().toString().padStart(2, '0')}${now
    .getMinutes()
    .toString()
    .padStart(2, '0')}${now.getSeconds().toString().padStart(2, '0')}`
}

const departmentDialogVisible = ref(false)
const tempDepartmentPath = ref<(string | number)[]>([])
const tempDepartmentBreadcrumb = ref('')

const openDepartmentDialog = () => {
  departmentDialogVisible.value = true
  tempDepartmentPath.value = [...formModel.departmentPath]
  tempDepartmentBreadcrumb.value = formModel.departmentBreadcrumb
}

const handleDepartmentNodeClick = (_data: DepartmentNode, node: any) => {
  const pathNodes: DepartmentNode[] = []
  let current = node
  while (current && current?.data) {
    pathNodes.unshift(current.data as DepartmentNode)
    current = current.parent
  }
  tempDepartmentPath.value = pathNodes.map((item) => item.value)
  tempDepartmentBreadcrumb.value = pathNodes.map((item) => item.label).join(' / ')
}

const confirmDepartmentSelection = () => {
  if (!tempDepartmentPath.value.length) {
    ElMessage.warning('请选择具体的检验部门')
    return
  }
  formModel.departmentPath = [...tempDepartmentPath.value]
  formModel.departmentBreadcrumb = tempDepartmentBreadcrumb.value
  departmentDialogVisible.value = false

  const lastValue = tempDepartmentPath.value[tempDepartmentPath.value.length - 1]
  if (lastValue !== undefined && lastValue !== null) {
    fetchInspectorList(Number(lastValue))
  }
}

const cancelDepartmentSelection = () => {
  departmentDialogVisible.value = false
}

const openInspectorDialog = () => {
  if (!formModel.departmentPath.length) {
    ElMessage.warning('请先选择检验部门')
    return
  }
  inspectorDialogVisible.value = true
  inspectorSelection.value = [...formModel.inspectors]
}

const handleInspectorSelection = (rows: InspectorUser[]) => {
  inspectorSelection.value = rows
}

const removeInspector = (userId: number) => {
  formModel.inspectors = formModel.inspectors.filter((item) => item.userId !== userId)
}

const removeDialogInspector = (userId: number) => {
  inspectorSelection.value = inspectorSelection.value.filter((item) => item.userId !== userId)
}

const clearInspectorSelection = () => {
  inspectorSelection.value = []
}

const confirmInspectors = () => {
  if (!inspectorSelection.value.length) {
    ElMessage.warning('请选择检验人员')
    return
  }
  formModel.inspectors = [...inspectorSelection.value]
  inspectorDialogVisible.value = false
}

const handleInspectorSearch = () => {
  // computed 会自动处理
}

const fetchInspectorList = async (organId: number) => {
  try {
    const { data } = await https.Reads.get<ApiResultResponse<any[]>>('/RBAC/ShowOrganUser', {
      params: { organid: organId }
    })
    if (data.code === 1 && data.data?.length) {
      inspectorList.value = data.data
        .map((item) => ({
          userId: item.userId ?? item.UserId ?? item.id,
          userName: item.userName ?? item.UserName ?? item.username ?? ''
        }))
        .filter((item) => item.userId && item.userName)
    } else {
      inspectorList.value = []
    }
  } catch (error: any) {
    console.error(error)
    inspectorList.value = []
  }
}

// 打开生产计划选择对话框
const openPlanDialog = () => {
  planDialogVisible.value = true
  currentPlan.value = null
}

// 获取生产计划列表
const fetchPlanList = async () => {
  planTableLoading.value = true
  try {
    const params: Record<string, any> = {
      pageIndex: planPagination.pageIndex,
      pageSize: planPagination.pageSize
    }
    if (planQueryForm.keyword) {
      params.keyword = planQueryForm.keyword
    }
    if (planQueryForm.productName) {
      params.productName = planQueryForm.productName
    }
    const { data } = await https.Reads.get<ApiPageResponse<any>>('/AProduction_Plan/GetPlanPage', {
      params
    })
    if (data.code === 1) {
      planTableData.value = data.data || []
      planPagination.totalCount = data.totalCount || planTableData.value.length
    } else {
      planTableData.value = []
      planPagination.totalCount = 0
      ElMessage.error(data.msg || '获取生产计划失败')
    }
  } catch (error: any) {
    console.error(error)
    planTableData.value = []
    ElMessage.error(error?.message || '获取生产计划失败')
  } finally {
    planTableLoading.value = false
  }
}

const handlePlanQuery = () => {
  planPagination.pageIndex = 1
  fetchPlanList()
}

const resetPlanQuery = () => {
  planQueryForm.keyword = ''
  planQueryForm.productName = ''
  handlePlanQuery()
}

const handlePlanRowChange = (row: any | null) => {
  currentPlan.value = row
}

const handlePlanSizeChange = (size: number) => {
  planPagination.pageSize = size
  fetchPlanList()
}

const handlePlanPageChange = (page: number) => {
  planPagination.pageIndex = page
  fetchPlanList()
}

// 确认选择生产计划
const handlePlanConfirm = async () => {
  if (!currentPlan.value) {
    ElMessage.warning('请选择生产计划')
    return
  }
  const plan = currentPlan.value
  formModel.planId = plan.id
  formModel.planCode = plan.planCode
  formModel.planName = plan.planName
  
  // 填充产品信息
  formModel.productId = plan.productId ? Number(plan.productId) : undefined
  formModel.productCode = plan.productId || ''
  formModel.productName = plan.productName || ''
  formModel.specification = plan.productmodelsame || ''
  formModel.unit = plan.productunit || ''
  
  // 从生产计划关联的工单中获取第一个工单信息（如果有）
  // 优先从本地存储查找该计划分解的工单
  try {
    const stored = localStorage.getItem('production_work_orders')
    if (stored) {
      const localOrders = JSON.parse(stored) as any[]
      // 查找该计划关联的工单
      const planWorkOrders = localOrders.filter(o => o.planId === plan.id || o.planName === plan.planName)
      if (planWorkOrders.length > 0) {
        // 使用第一个工单的信息
        const firstWorkOrder = planWorkOrders[0]
        formModel.workOrderId = firstWorkOrder.id
        formModel.workOrderCode = firstWorkOrder.orderCode
        formModel.workOrderName = firstWorkOrder.orderName
      } else {
        // 如果没有找到工单，使用计划名称作为工单名称
        formModel.workOrderCode = ''
        formModel.workOrderName = `${plan.planName}-工单`
      }
    } else {
      // 如果没有本地存储，使用计划名称作为工单名称
      formModel.workOrderCode = ''
      formModel.workOrderName = `${plan.planName}-工单`
    }
  } catch (error) {
    console.warn('获取工单信息失败:', error)
    formModel.workOrderCode = ''
    formModel.workOrderName = `${plan.planName}-工单`
  }
  
  planDialogVisible.value = false
  
  // 根据产品ID获取检测方案
  if (formModel.productId) {
    fetchPlanInfo(formModel.productId)
  } else if (formModel.productCode) {
    // 如果只有产品编号，先查找产品ID
    fetchProductIdByCode(formModel.productCode)
  }
}

const fetchProductIdByCode = async (productCode: string) => {
  try {
    const { data } = await https.Reads.get<ApiPageResponse<any>>('/Product/ProductGetList', {
      params: {
        productcard: productCode,
        pageindex: 1,
        pagesize: 1
      }
    })
    if (data.code === 1 && data.data?.length) {
      const product = data.data[0]
      formModel.productId = product.id
      fetchPlanInfo(product.id)
    } else {
      ElMessage.warning('未找到对应的产品信息')
    }
  } catch (error: any) {
    console.error('获取产品ID失败:', error)
    ElMessage.error('获取产品信息失败')
  }
}

const fetchPlanInfo = async (productId: number) => {
  planLoading.value = true
  planInfo.value = null
  planItems.value = []
  try {
    const { data } = await https.Reads.get<ApiResultResponse<WorkOrderInspectionPlan | null>>(
      '/ProductInspection/ProductPlanInfo',
      { params: { productid: productId } }
    )
    if (data.code === 1 && data.data) {
      planInfo.value = data.data
      formModel.inspectionName ||= `${formModel.planName || formModel.workOrderName}工单检验`
      planItems.value = (data.data.items || []).map((item) => ({
        ...item,
        measuredvalue: '',
        result: '合格'
      }))
    } else {
      planInfo.value = null
      planItems.value = []
      ElMessage.warning(data.msg || '该产品未配置检测方案')
    }
  } catch (error: any) {
    console.error(error)
    planInfo.value = null
    planItems.value = []
    ElMessage.error(error?.message || '获取检测方案失败')
  } finally {
    planLoading.value = false
  }
}

const autoCalcQualifiedQty = () => {
  if (
    formModel.inspectionQty !== null &&
    formModel.unqualifiedQty !== null &&
    formModel.inspectionQty >= formModel.unqualifiedQty
  ) {
    formModel.qualifiedQty = formModel.inspectionQty - formModel.unqualifiedQty
  }
}

const autoCalcResult = () => {
  if (planInfo.value?.enablemaxunqualified && planInfo.value.maxunqualifiedcount != null) {
    if (formModel.unqualifiedQty != null) {
      formModel.resultStatus =
        formModel.unqualifiedQty > planInfo.value.maxunqualifiedcount ? '不合格' : '合格'
    }
  } else {
    formModel.resultStatus = formModel.unqualifiedQty && formModel.unqualifiedQty > 0 ? '不合格' : '合格'
  }
}

watch(
  () => [formModel.inspectionQty, formModel.unqualifiedQty],
  () => {
    autoCalcQualifiedQty()
    autoCalcResult()
  }
)

const buildSubmitPayload = () => {
  if (!planInfo.value) {
    throw new Error('未获取到检测方案，无法提交')
  }
  const departmentId = formModel.departmentPath[formModel.departmentPath.length - 1]
  return {
    inspectioncode: formModel.inspectionCode,
    issystemcode: formModel.useSystemCode,
    inspectionname: formModel.inspectionName,
    inspectiondate: formModel.inspectionDate,
    departmentid: Number(departmentId),
    departmentpath: formModel.departmentBreadcrumb,
    departmentname: formModel.departmentBreadcrumb.split(' / ').pop() || '',
    inspectors: formModel.inspectors.map((item) => ({
      userid: item.userId,
      username: item.userName
    })),
    remark: formModel.remark || formModel.resultRemark,
    planid: formModel.planId, // 生产计划ID
    plancode: formModel.planCode, // 生产计划编号
    planname: formModel.planName, // 生产计划名称
    workorderid: formModel.workOrderId,
    workordercode: formModel.workOrderCode,
    workordername: formModel.workOrderName,
    productid: formModel.productId,
    productcode: formModel.productCode,
    productname: formModel.productName,
    specification: formModel.specification,
    unit: formModel.unit,
    batchno: formModel.batchNo,
    // 检测方案信息
    detectionplanid: planInfo.value.planid,
    detectionplancode: planInfo.value.plancode,
    detectionplanname: planInfo.value.planname,
    enabledefectsetting: planInfo.value.enabledefectsetting,
    enablemaxunqualified: planInfo.value.enablemaxunqualified,
    maxunqualifiedcount: planInfo.value.maxunqualifiedcount,
    enablecriticaldefectrate: planInfo.value.enablecriticaldefectrate,
    criticaldefectrate: planInfo.value.criticaldefectrate,
    enablemajordefectrate: planInfo.value.enablemajordefectrate,
    majordefectrate: planInfo.value.majordefectrate,
    enableminordefectrate: planInfo.value.enableminordefectrate,
    minordefectrate: planInfo.value.minordefectrate,
    inspectionqty: formModel.inspectionQty,
    qualifiedqty: formModel.qualifiedQty,
    unqualifiedqty: formModel.unqualifiedQty,
    criticaldefectqty: formModel.criticalDefectQty,
    majordefectqty: formModel.majorDefectQty,
    minordefectqty: formModel.minorDefectQty,
    inspectionresult: formModel.resultStatus,
    items: planItems.value.map((item) => ({
      planitemid: item.id,
      testitemid: item.testitemid,
      testitemcard: item.testitemcard,
      testitemname: item.testitemname,
      detectiontypename: item.detectiontypename,
      detectiontoolname: item.detectiontoolname,
      detectionrequirement: item.detectionrequirement,
      standardvalue: item.standardvalue,
      unit: item.unit,
      toleranceupper: item.toleranceupper,
      tolerancelower: item.tolerancelower,
      measuredvalue: item.measuredvalue,
      result: item.result,
      sortorder: item.sortorder
    }))
  }
}

const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    if (!planInfo.value) {
      ElMessage.warning('请选择已配置检测方案的生产计划')
      return
    }
    if (!formModel.planId) {
      ElMessage.warning('请选择生产计划')
      return
    }
    submitLoading.value = true
    try {
      const payload = buildSubmitPayload()
      const { data } = await https.Writes.post<ApiResultResponse<number>>(
        '/Detection/WorkOrderInspectionAdd',
        payload
      )
      if (data.code === 1) {
        ElMessage.success('工单检验新增成功')
        router.back()
      } else {
        throw new Error(data.msg || '保存失败')
      }
    } catch (error: any) {
      console.error(error)
      ElMessage.error(error?.message || '保存失败')
    } finally {
      submitLoading.value = false
    }
  })
}

const handleBack = () => {
  router.back()
}

const fetchDepartmentTree = async () => {
  try {
    const { data } = await https.Reads.get<ApiResultResponse<DepartmentNode[]>>('/Organtion/Binds')
    if (data.code === 1) {
      departmentOptions.value = data.data || []
    }
  } catch (error) {
    console.error(error)
  }
}

onMounted(() => {
  handleCodeModeChange()
  fetchDepartmentTree()
})
</script>

<style scoped>
.work-order-inspection-page {
  min-height: calc(100vh - 60px);
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  background: linear-gradient(135deg, #f0f4ff 0%, #fef5f6 45%, #fdf8ff 100%);
}

.card-block {
  width: 100%;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(15, 36, 70, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.6);
}

.form-card {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-desc {
  margin: 0;
  color: #909399;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.system-flag {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #909399;
}

.inspection-form :deep(.el-form-item) {
  margin-bottom: 16px;
}

.inspectors-input {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  min-height: 36px;
}

.inspectors-input .el-tag {
  margin-right: 4px;
}

.department-selector {
  display: flex;
  gap: 8px;
}

.department-selector .el-input {
  flex: 1;
}

.mb-12 {
  margin-bottom: 12px;
}

.inspector-dialog {
  display: flex;
  gap: 16px;
  min-height: 420px;
}

.inspector-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.inspector-right {
  width: 240px;
  border-left: 1px solid #ebeef5;
  padding-left: 16px;
  display: flex;
  flex-direction: column;
}

.inspector-right-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.inspector-tag-list {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  overflow-y: auto;
}

.dialog-filter {
  margin-bottom: 12px;
}
</style>

